# import torch
# from torchvision import models, transforms
# from PIL import Image
# import json
# import torch.optim as optim
# import torch.nn as nn
#
# MODEL_PATH = 'D:/secondary_trading_platform/secondhand/backend/myapp/resnet50-0676ba61.pth'
# LABEL_PATH = 'D:/secondary_trading_platform/secondhand/backend/myapp/imagenet_class_index.json'
#
#
# class ImageRecognizer:
#     def __init__(self, fine_tune=False):
#         self.model = models.resnet50(pretrained=False)
#         self.model.load_state_dict(torch.load(MODEL_PATH, map_location=torch.device('cpu'), weights_only=True))
#
#         if fine_tune:
#             # 微调模型：冻结前面的层，只训练最后的全连接层
#             for param in self.model.parameters():
#                 param.requires_grad = False
#             self.model.fc = nn.Linear(self.model.fc.in_features, 1000)  # 假设你有1000个类别
#
#         self.model.eval()
#
#         self.labels = self._load_labels()
#
#         self.transform = transforms.Compose([
#             transforms.Resize(256),
#             transforms.CenterCrop(224),
#             transforms.ToTensor(),
#             transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
#         ])
#
#     def _load_labels(self):
#         with open(LABEL_PATH) as f:
#             return {int(k): v[1] for k, v in json.load(f).items()}
#
#     def predict(self, image_path):
#         img = Image.open(image_path).convert('RGB')
#         img_t = self.transform(img).unsqueeze(0)
#
#         with torch.no_grad():
#             outputs = self.model(img_t)
#             _, pred = torch.max(outputs, 1)
#
#         return self.labels[pred.item()]
#
#
# def test_image_recognizer(image_path, fine_tune=False):
#     recognizer = ImageRecognizer(fine_tune=fine_tune)
#     try:
#         print(f"正在识别图片: {image_path}")
#         item_name = recognizer.predict(image_path)
#         print(f"识别结果: {item_name}")
#     except Exception as e:
#         print(f"识别失败: {e}")
#
#
# if __name__ == "__main__":
#     image_path = "D:/secondary_trading_platform/secondhand/backend/myapp/static/img/1.jpg"
#     test_image_recognizer(image_path, fine_tune=True)  # 开启微调模式